package gy.com.sansharescuesystem.fragment;

import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.baidu.mapapi.SDKInitializer;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import gy.com.sansharescuesystem.R;
import gy.com.sansharescuesystem.adapter.HistoryAdapter;
import gy.com.sansharescuesystem.base.BaseFragment;
import gy.com.sansharescuesystem.callback.AcyncCallBack;
import gy.com.sansharescuesystem.entity.RescueListResData;
import gy.com.sansharescuesystem.entity.RescueListResult;
import gy.com.sansharescuesystem.modle.QueryModel;
import gy.com.sansharescuesystem.modle.impl.QueryModelImpl;
import gy.com.sansharescuesystem.utils.DialogUtils;
import gy.com.sansharescuesystem.utils.UIUtils;


public class HistoryFragment extends BaseFragment {
    private PullToRefreshListView mListView;
    private HistoryAdapter adapter;
    private RescueListResult mHistoryBean;
    private List<RescueListResData> mHistoryDatas = new ArrayList<>();
    private QueryModel model = new QueryModelImpl();
    private int mCurrentPageIndex=0;
    //船只编号
    private EditText shipNoEdt;
    //事故种类
    private EditText accidentKindEdt;
    //事故状态
    private Spinner accidentStatusSpinner;
    private ImageView searchImgView;
    private LinearLayout searchLayout;
    private Dialog waitDialog;
    // 已报警：1； 已接警：2；救援中：3；救援成功：4；救援失败：5，取消：6,约定status=8时间查询状态为1，2，3这三种集合；约定status=7时间查询状态为4，5，6这三种集合
    String[] mItems ={"事故状态","已报警","已接警","救援中","救援成功","救援失败","取消"};
    //上一次的输入的值
    private String shipNOstr,accidentKindStr,accidentStatusSpinnerStr;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case GET_HISTORY_DATA_SUCCESS:
                    DialogUtils.closeDialog(waitDialog);
                    if(msg.obj!=null){
                        mHistoryBean = (RescueListResult) msg.obj;
                        List<RescueListResData> data = mHistoryBean.getData();
                        if(mHistoryBean.getFlag()==0){
                            mHistoryDatas.clear();
                            UIUtils.showToast(getActivity(),mHistoryBean.getMsg());
                        }else{
                            if(msg.arg1==FIRST_OR_REFRESH_DATA){
                                mHistoryDatas.clear();
                                mHistoryDatas.addAll(data);
                                mCurrentPageIndex=0;
                            }else{
                                mCurrentPageIndex = mHistoryDatas.size()-1;
                                if(mPage==Integer.parseInt(mHistoryBean.getCurrent())){
                                    if(data.size()!=0){
                                        mHistoryDatas.addAll(data);
                                    }else{
                                        UIUtils.showToast(getActivity(),"没有更多数据");
                                    }
                                }else{
                                    if(data.size()!=0){

                                        mHistoryDatas.addAll(data);
                                    }else{
                                        UIUtils.showToast(getActivity(),"没有更多数据");
                                    }
//                                    UIUtils.showToast(getActivity(),"没有更多数据");
                                }
                            }
                        }
                    }else{
                        UIUtils.showToast(getActivity(),"获取数据失败");
                    }
                    mListView.onRefreshComplete();
                    showListView();
                    break;
                case GET_HISTORY_DATA_FAILED:
                    DialogUtils.closeDialog(waitDialog);
                    UIUtils.showToast(getActivity(),"获取信息失败");
                    mListView.onRefreshComplete();
                    break;


            }
        }
    };
    private static final int GET_HISTORY_DATA_SUCCESS = 11;
    private static final int GET_HISTORY_DATA_FAILED = 12;
    private static final int FIRST_OR_REFRESH_DATA = 0;
    private static final int GET_NEXT_PAGE = 123;
    private int mPage=1;



    @Override
    protected View onCreateView(LayoutInflater inflater) {
        SDKInitializer.initialize(mActivity.getApplicationContext());
        View view = inflater.inflate(R.layout.fragment_history,null);

        return view;
    }

    @Override
    protected void initView() {
        mListView = (PullToRefreshListView) findViewById(R.id.lv_history_list);
        shipNoEdt= (EditText) findViewById(R.id.ship_no_edt);
        accidentKindEdt= (EditText) findViewById(R.id.accident_kind_edt);
        accidentStatusSpinner= (Spinner) findViewById(R.id.accident_status_spinner);
        searchImgView= (ImageView) findViewById(R.id.search_history_imgvw);
        searchLayout= (LinearLayout) findViewById(R.id.search_layout);

    }

    @Override
    protected void setWidgetListener() {
        mListView.setMode(PullToRefreshBase.Mode.BOTH);
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {

                if(mListView.isHeaderShown()){
                    if(!shipNoEdt.getText().toString().equals("") || !accidentKindEdt.getText().toString().equals("")
                            || !accidentStatusSpinner.getSelectedItem().equals("事故状态")) {
                        mPage=1;
                        search(shipNoEdt.getText().toString(), accidentKindEdt.getText().toString(), accidentStatusSpinner.getSelectedItem().toString());
                    }else {
                        getDataByPage(FIRST_OR_REFRESH_DATA);
                    }
                }else if(mListView.isFooterShown()){
                    if(!shipNoEdt.getText().toString().equals("") || !accidentKindEdt.getText().toString().equals("")
                            || !accidentStatusSpinner.getSelectedItem().equals("事故状态")) {
                        mPage++;
                        search(shipNoEdt.getText().toString(), accidentKindEdt.getText().toString(), accidentStatusSpinner.getSelectedItem().toString());
                    }else {
                        getDataByPage(GET_NEXT_PAGE);
                    }
                }
            }
        });
        searchLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!shipNoEdt.getText().toString().equals("") || !accidentKindEdt.getText().toString().equals("")
                        || !accidentStatusSpinner.getSelectedItem().equals("事故状态")) {
                    if(!shipNoEdt.getText().toString().equals(shipNOstr) || !accidentKindEdt.getText().toString().equals(accidentKindStr) ||
                    !accidentStatusSpinner.getSelectedItem().toString().equals(accidentStatusSpinnerStr))
                        mPage=1;
                    if(shipNoEdt.getText().toString().equals(shipNOstr)&&accidentKindEdt.getText().toString().equals(accidentKindStr) &&
                            accidentStatusSpinner.getSelectedItem().toString().equals(accidentStatusSpinnerStr))
                        mPage=1;
                    search(shipNoEdt.getText().toString(), accidentKindEdt.getText().toString(), accidentStatusSpinner.getSelectedItem().toString());
                }else{
                    UIUtils.showToast(getActivity(),"请输入或选择查询条件");
                }
            }
        });
    }


    @Override
    protected void initData() {

        List accidentStatusList=new ArrayList();
        for(int i=0;i<mItems.length;i++){
            accidentStatusList.add(mItems[i]);
        }

        final ArrayAdapter spinnerAdapter=new ArrayAdapter(this.getContext(), android.R.layout.simple_spinner_dropdown_item,accidentStatusList);
        accidentStatusSpinner.setAdapter(spinnerAdapter);


        accidentStatusSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
            TextView tv = (TextView)view;
            if(((TextView) view).getText().toString().equals("事故状态"))
            tv.setTextColor(getResources().getColor(R.color.history_hint));

            tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,15);    //设置大小

            tv.setGravity(Gravity.CENTER);

        }
        @Override
        public void onNothingSelected(AdapterView<?> parent){}
    });
    getDataByPage(FIRST_OR_REFRESH_DATA);
    }
    private void getDataByPage(final int flag){
        if(flag==0){
            mPage=1;
        }else{
            mPage = mPage+1;
        }
        model.queryHistoryList(new AcyncCallBack() {
            @Override
            public void onSuccess(Object obj) {
                Message msg = new Message();
                msg.what = GET_HISTORY_DATA_SUCCESS;
                msg.obj = obj;
                msg.arg1 = flag;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onFailed() {
                mHandler.sendEmptyMessage(GET_HISTORY_DATA_FAILED);
            }
        },mPage+"");
    }
    private void showListView(){
        if(adapter==null){
            adapter = new HistoryAdapter(getActivity(),mHistoryDatas,mListView);
        }
        adapter.notifyDataSetChanged();
        mListView.setAdapter(adapter);
        mListView.getRefreshableView().setSelection(mCurrentPageIndex);
    }
    private  void search(String shipNo,String accidentKind,String accidentStatus){
        shipNOstr=shipNo;
        accidentStatusSpinnerStr=accidentStatus;
        accidentKindStr=accidentKind;
        waitDialog=DialogUtils.createLoadingDialog(this.getContext(),"加载中...",false);
        Map<String,String> map=new HashMap<String,String>();
        map.put("iship",shipNo);
        map.put("a_type",accidentKind);
        //已报警：1； 已接警：2；救援中：3；救援成功：4；救援失败：5，取消：6,
        if(accidentStatus.equals("已报警")){
            accidentStatus="1";
        }else if(accidentStatus.equals("已接警")){
            accidentStatus="2";
        }else if(accidentStatus.equals("救援中")){
            accidentStatus="3";
        }else if(accidentStatus.equals("救援成功")){
            accidentStatus="4";
        }else if(accidentStatus.equals("救援失败")){
            accidentStatus="5";
        }else if(accidentStatus.equals("取消")){
            accidentStatus="6";
        }
        map.put("status",accidentStatus);
        map.put("page",mPage+"");
        model.searchHistory(new AcyncCallBack() {
            @Override
            public void onSuccess(Object obj) {
                Message msg = new Message();
                msg.what = GET_HISTORY_DATA_SUCCESS;
                msg.obj = obj;
                if(mPage==1){
                    msg.arg1 = FIRST_OR_REFRESH_DATA;
                }else{
                    msg.arg1 = GET_NEXT_PAGE;
                }

                mHandler.sendMessage(msg);
            }

            @Override
            public void onFailed() {
                mHandler.sendEmptyMessage(GET_HISTORY_DATA_FAILED);
            }
        },map);
    }



    @Override
    protected void onBackPressed() {
        super.onBackPressed();
        Log.i("onBackPressed:","press back key");
        DialogUtils.closeDialog(waitDialog);
    }


    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
